<?php
namespace app\admin\controller\operator;

use app\admin\controller\Controller;
use think\Db;

/**
 * 数据分析
 * Class Data
 * @package app\admin\controller\statistics
 */
class Agent extends Controller
{

    /**
     * 品牌商列表
     * @return mixed
     * @throws \think\Exception
     */
    public function agent(){

        $param = $this->request->param();

        //品牌商列表
        $where = [];
        if (isset($param['search']) && !empty($param['search'])) {
            $where["company_name"]= ["like",'%'.trim($param['search']).'%'];
        }
        //平台总分润
        $plant = db('divide_system')->where(['status'=>1])->sum('amount');
        //品牌商列表
        $list = db('agent')
            ->where(['type'=>0,'active'=>1,'is_recycle'=>0,'is_delete'=>0])
            ->where($where)
            ->field('agent_id,type,company_name,real_name,company_tel,recommend_id,agent_check_status,admin_check_status,create_time')
            ->order('create_time desc')
            ->paginate(15, false, [
                'query' => request()->request()
            ])->each(function($item,$key){

                //计算大代理个数，即城市运营商
                $item['maxganet'] = Db::name('agent')
                    ->where(['type'=>1,'active'=>1,'recommend_id'=>$item['agent_id'],'is_recycle'=>0,'is_delete'=>0])
                    ->count();

                //计算小代理个数，即城市合伙人
                $item['minganet'] = Db::name('agent')
                    ->where(['type'=>2,'active'=>1,'recommend_id'=>$item['agent_id'],'is_recycle'=>0,'is_delete'=>0])
                    ->count();

                //计算品牌商直接推荐的商户的个数
                $item['agentstore'] = Db::name('wxapp')
                    ->where(['active'=>1,'agent_id'=>$item['agent_id']])
                    ->count();

                //计算品牌商直接推荐的员推荐的商户的个数
                $agent_clerk_list =  Db::name('agent')
                    ->where(['type'=>3,'active'=>1,'recommend_id'=>$item['agent_id'],'is_recycle'=>0,'is_delete'=>0])
                    ->select();

                $clerk_num = 0;
                foreach ($agent_clerk_list as $kk=>&$vv){
                    $clerk_num+=  Db::name('wxapp')
                        ->where(['active'=>1,'agent_id'=>$vv['agent_id']])
                        ->count();
                }

                $item['clerk_num'] =   $clerk_num;

                //计算品牌商分润
                $item['agentmoney'] = Db::name('divide_service')
                    ->where(['agent_id'=>$item['agent_id'],'status'=>1])
                    ->sum('amount');

                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);

                return $item;
            });

        return $this->fetch('agent', compact( 'list','plant'));
    }



    /**
     * 运营商
     * @return mixed
     * @throws \think\Exception
     */
    public function one(){

        $param = $this->request->param();

        $where = ['recommend_id'=>$param['agent_id']];
        if (isset($param['search']) && !empty($param['search'])) {
            $where["company_name|real_name"]= ["like",'%'.trim($param['search']).'%'];
        }
        //运营商列表
        $list = db('agent')
            ->where(['type'=>1,'active'=>1,'is_recycle'=>0,'is_delete'=>0])
            ->where($where)
            ->field('agent_id,type,company_name,real_name,company_tel,recommend_id,agent_check_status,admin_check_status,create_time')
            ->order('create_time desc')
            ->paginate(15, false, [
                'query' => request()->request()
            ])->each(function($item,$key){


                //计算运营商直接推荐的商户的个数
                $item['agentstore'] = Db::name('wxapp')
                    ->where(['active'=>1,'agent_id'=>$item['agent_id']])
                    ->count();
                //计算小代理个数，即城市合伙人
                $item['minganet'] = Db::name('agent')
                    ->where(['type'=>2,'active'=>1,'recommend_id'=>$item['agent_id'],'is_recycle'=>0,'is_delete'=>0])
                    ->count();

                //计算运营商分润
                $item['agentmoney'] = Db::name('divide_service')
                    ->where(['agent_id'=>$item['agent_id'],'status'=>1])
                    ->sum('amount');

                //计算运营商直接推荐的员推荐的商户的个数
                $agent_clerk_list =  Db::name('agent')
                    ->where(['type'=>3,'active'=>1,'recommend_id'=>$item['agent_id'],'is_recycle'=>0,'is_delete'=>0])
                    ->select();

                $clerk_num = 0;
                foreach ($agent_clerk_list as $kk=>&$vv){
                    $clerk_num+=  Db::name('wxapp')
                        ->where(['active'=>1,'agent_id'=>$vv['agent_id']])
                        ->count();
                }

                $item['clerk_num'] =   $clerk_num;

                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);

                return $item;
            });

        return $this->fetch('one', compact( 'list'));
    }





    /**
     * 合伙人
     * @return mixed
     * @throws \think\Exception
     */
    public function tow(){


        $param = $this->request->param();

        $where = ['recommend_id'=>$param['agent_id']];
        if (isset($param['search']) && !empty($param['search'])) {
            $where["company_name|real_name"]= ["like",'%'.trim($param['search']).'%'];
        }
        //合伙人列表
        $list = db('agent')
            ->where(['type'=>2,'active'=>1,'is_recycle'=>0,'is_delete'=>0])
            ->where($where)
            ->field('agent_id,type,company_name,real_name,company_tel,recommend_id,agent_check_status,admin_check_status,create_time')
            ->order('create_time desc')
            ->paginate(15, false, [
                'query' => request()->request()
            ])->each(function($item,$key){


                //计算品牌商推荐的商户的个数
                $item['agentstore'] = Db::name('wxapp')
                    ->where(['active'=>1,'agent_id'=>$item['agent_id']])
                    ->count();

                //计算品牌商分润
                $item['agentmoney'] = Db::name('divide_service')
                    ->where(['agent_id'=>$item['agent_id'],'status'=>1])
                    ->sum('amount');

                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);

                //计算运营商直接推荐的员推荐的商户的个数
                $agent_clerk_list =  Db::name('agent')
                    ->where(['type'=>3,'active'=>1,'recommend_id'=>$item['agent_id'],'is_recycle'=>0,'is_delete'=>0])
                    ->select();

                $clerk_num = 0;
                foreach ($agent_clerk_list as $kk=>&$vv){
                    $clerk_num+=  Db::name('wxapp')
                        ->where(['active'=>1,'agent_id'=>$vv['agent_id']])
                        ->count();
                }

                $item['clerk_num'] =   $clerk_num;

                return $item;
            });

        return $this->fetch('tow', compact( 'list'));
    }

    /**
     * 数据导出
     */
    public function export(){
        if (! $this->exportList()) {
            return $this->renderError('操作失败');
        }
        return $this->exportList();
    }

    private function exportList(){
        header("Content-type:text/html;charset=utf-8");
        $mpName = '数据';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = 1;
        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
            '品牌商ID', '品牌商名称', '品牌商电话', '品牌商分润', '运营商个数', '合伙人个数', '商家个数(直推)', '商家个数(员工推荐)', '添加时间',
        ];

        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');


        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.xlsx', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.xlsx'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->agentData();

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }

/*
 * 获取品牌商统计数据
 */
    public function agentData(){

        $param = $this->request->param();

        //品牌商列表
        $where = [];
        if (isset($param['search']) && !empty($param['search'])) {
            $where["company_name"]= ["like",'%'.trim($param['search']).'%'];
        }
        //平台总分润
        $plant = db('divide_system')->where(['status'=>1])->sum('amount');
        //品牌商列表
        $list = db('agent')
            ->where(['type'=>0,'active'=>1,'is_recycle'=>0,'is_delete'=>0])
            ->where($where)
            ->field('agent_id,type,company_name,real_name,company_tel,recommend_id,agent_check_status,admin_check_status,create_time')
            ->order('create_time desc')
            ->paginate(100, false, [
                'query' => request()->request()
            ])->each(function($item,$key){

                //计算大代理个数，即城市运营商
                $item['maxganet'] = Db::name('agent')
                    ->where(['type'=>1,'active'=>1,'recommend_id'=>$item['agent_id'],'is_recycle'=>0,'is_delete'=>0])
                    ->count();

                //计算小代理个数，即城市合伙人
                $item['minganet'] = Db::name('agent')
                    ->where(['type'=>2,'active'=>1,'recommend_id'=>$item['agent_id'],'is_recycle'=>0,'is_delete'=>0])
                    ->count();

                //计算品牌商直接推荐的商户的个数
                $item['agentstore'] = Db::name('wxapp')
                    ->where(['active'=>1,'agent_id'=>$item['agent_id']])
                    ->count();

                //计算品牌商直接推荐的员推荐的商户的个数
                $agent_clerk_list =  Db::name('agent')
                    ->where(['type'=>3,'active'=>1,'recommend_id'=>$item['agent_id'],'is_recycle'=>0,'is_delete'=>0])
                    ->select();

                $clerk_num = 0;
                foreach ($agent_clerk_list as $kk=>&$vv){
                    $clerk_num+=  Db::name('wxapp')
                        ->where(['active'=>1,'agent_id'=>$vv['agent_id']])
                        ->count();
                }

                $item['clerk_num'] =   $clerk_num;

                //计算品牌商分润
                $item['agentmoney'] = Db::name('divide_service')
                    ->where(['agent_id'=>$item['agent_id'],'status'=>1])
                    ->sum('amount');

                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);

                return $item;
            });
        foreach($list as $order){
            $dataArray[] = [
                '品牌商ID' => $this->filterValue($order['agent_id']),
                '品牌商名称' => $this->filterValue(empty($order['company_name'])?$order['real_name']:$order['company_name']),
                '品牌商电话' => $this->filterValue($order['company_tel']),
                '品牌商分润' => $this->filterValue($order['agentmoney']),
                '运营商个数' => $this->filterValue($order['maxganet']),
                '合伙人个数' => $this->filterValue($order['minganet']),
                '商家个数(直推)' => $this->filterValue($order['agentstore']),
                '商家个数(员工推荐)' => $this->filterValue($order['clerk_num']),
                '添加时间' => $this->filterValue($order['create_time']),
            ];
        }
        return $dataArray;
    }
    /**
     * 所有数据导出
     */
    public function allexport(){
        if (! $this->allexportList()) {
            return $this->renderError('操作失败');
        }
        return $this->allexportList();
    }
    /*
     * 获取所有代理数据
     */
    public function allAgentData(){
        $param = $this->request->param();
        //品牌商列表
        $where = [];
        if (isset($param['search']) && !empty($param['search'])) {
            $where["company_name"]= ["like",'%'.trim($param['search']).'%'];
        }
        //品牌商列表
        $list = Db::table('yoshop_agent')
            ->alias('a')
            ->join('yoshop_divide_service s','a.agent_id = s.agent_id')
            ->where('s.status','=',1)
            ->where('a.type','in','0,1,2')
            ->group('s.agent_id')
            ->field('a.*,SUM(s.amount) as totalMoney')
            ->select();
        foreach($list->toArray() as $order){
            if($order['type']==0){
                $info='品牌商';
            }elseif ($order['type']==1){
                $info='运营商';
            }else{
                $info='合伙人';
            }
            $dataArray[] = [
                '代理ID' => $this->filterValue($order['agent_id']),
                '代理类型'=>$this->filterValue($info),
                '代理名称' => $this->filterValue(empty($order['company_name'])?$order['real_name']:$order['company_name']),
                '代理电话' => $this->filterValue($order['company_tel']),
                '代理分润' => $this->filterValue($order['totalMoney']),
                '添加时间' => $this->filterValue(date('Y-m-d h:i:s',$order['create_time'])),
            ];
        }
        return $dataArray;
    }
    private function allexportList(){
        header("Content-type:text/html;charset=utf-8");
        $mpName = '所有代理数据';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = 1;
        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
            '代理ID','代理类型', '代理名称', '代理电话', '代理分润', '添加时间',
        ];

        $fileName = $mpName . date('Y-m-d');// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');


        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.xlsx', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.xlsx'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->allAgentData();

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }

    private function filterValue($value){
        return "\t" . $value . "\t";
    }
}